/**
 * $Id: DbUnitUtils.java 19 2011-06-11 04:06:06Z feigme $
 */
package com.iary.infrastructure.orm.hibernate;

import java.io.FileInputStream;

import javax.sql.DataSource;

import org.dbunit.database.DatabaseConnection;
import org.dbunit.database.IDatabaseConnection;
import org.dbunit.database.QueryDataSet;
import org.dbunit.dataset.IDataSet;
import org.dbunit.dataset.xml.FlatXmlDataSetBuilder;
import org.dbunit.dataset.xml.XmlDataSet;
import org.dbunit.operation.DatabaseOperation;
import org.springframework.core.io.ClassPathResource;
import org.springframework.jdbc.datasource.DataSourceUtils;

public class DbUnitUtils {

	static enum DBFmtType {
		xml, flat
	}

	private static IDatabaseConnection getIconn(DataSource dataSource)
			throws Exception {
		return new DatabaseConnection(DataSourceUtils.getConnection(dataSource));
	}

	public static QueryDataSet getActual(DataSource dataSource,
			String tableName, String query) throws Exception {
		QueryDataSet actual = new QueryDataSet(getIconn(dataSource));
		actual.addTable(tableName, query);
		return actual;
	}

	/**
	 * if type == flat, used XmlDataSet if type == xml, used FlatXmlDataSet
	 */
	public static IDataSet getExpected(String path, DBFmtType type)
			throws Exception {
		if (DBFmtType.xml.equals(type)) {
			return new XmlDataSet(new FileInputStream(new ClassPathResource(
					path).getFile()));
		} else if (DBFmtType.flat.equals(type)) {
			return new FlatXmlDataSetBuilder()
					.build(new ClassPathResource(path).getFile());
		}
		return null;
	}

	/**
	 * if type == flat, used XmlDataSet if type == xml, used FlatXmlDataSet
	 */
	public static void insert(DataSource dataSource, DBFmtType type,
			String... path) throws Exception {
		for (String xmlPath : path) {
			IDataSet data = null;
			if (DBFmtType.xml.equals(type)) {
				data = new XmlDataSet(new FileInputStream(
						new ClassPathResource(xmlPath).getFile()));
			} else if (DBFmtType.flat.equals(type)) {
				data = new FlatXmlDataSetBuilder().build(new ClassPathResource(
						xmlPath).getFile());
			}
			DatabaseOperation.INSERT.execute(getIconn(dataSource), data);
		}
	}

}
